package com.ken.zeratul.i18n.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.util.Locale;

/**
 * 将请求头解析单独拿出来处理，若是Gateway服务，则不加载该配置，因为LocaleResolver是Servlet环境的类，和Gateway不兼容
 */
@Slf4j
//设置自动装配的顺序，该装配类 必须比 WebMvcAutoConfiguration 先加载
//因为WebMvcAutoConfiguration里配置了国际化处理器Bean LocaleResolver
//会导致自己配置的LocaleResolver Bean对象不起作用
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
public class LocaleResolverConfiguration {

    /**
     * 当前语言环境，默认为zh-CN
     */
    @Value("${language.tag:zh-CN}")
    private String language;

    /**
     * 根据请求头Accept-Language切换语言环境
     * @return
     */
    @Bean
    @RefreshScope
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
        Locale defaultLocale = Locale.forLanguageTag(language);
        log.info("【国际化-语言环境】当前默认语言环境：{} - {}", language, defaultLocale);
        localeResolver.setDefaultLocale(defaultLocale);
        return localeResolver;
    }
}
